﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BaseSet.Data;
using BaseSet.Logic;
using BaseSet.Entity;
using BaseSet.Framework;
using BaseSet.Entity.Common;
using BaseSet.Entity.Common.Text;
using BaseSet;
using System.Data;


namespace WebSite.Blogs
{
    public partial class BlogAdd : System.Web.UI.Page
    {
        private string companyid = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            companyid = Request.QueryString["companyid"] + "";
            if (!Page.IsPostBack)
            {
                if (!string.IsNullOrEmpty(companyid))
                {
                    AddCompany(companyid);
                }
                BindBlogType();
                BindCompany();//加载小组
                BindBlogMaxPVMoney();
                LoadContent();//判断该用户是否存在保存的创作
            }
        }

        #region 加载博客类型
        private void BindBlogType()
        {
            BlogTypeHelper bthelper = new BlogTypeHelper();

            Criteria c = new Criteria();
            c.Add(CriteriaType.Equals, "Flag", 0);
            c.Add(CriteriaType.Equals, "BlogBigType", "图文");
            List<BlogType> list = bthelper.QueryBlogTypeBySearch(c, new Order[] { new Order("CreateDate", OrderMode.Desc) });
            //ddlBlogType.DataSource = list;
            //ddlBlogType.DataTextField = "BlogTypeName";
            //ddlBlogType.DataValueField = "ID";
            //ddlBlogType.DataBind();

            rblBlogType.DataSource = list;
            rblBlogType.DataTextField = "BlogTypeName";
            rblBlogType.DataValueField = "ID";
            rblBlogType.DataBind();

            rblBlogType.Items[0].Selected = true;

            //ListItem li = new ListItem();
            //li.Value = "-1";
            //li.Text = "-请选择-";
            //ddlBlogType.Items.Insert(0, li);
        }
        #endregion

        #region 加载博客单次浏览最大值
        private void BindBlogMaxPVMoney()
        {
            SystemConfig scinfo = new SystemConfig();
            SystemConfigHelper schelper = new SystemConfigHelper();
            scinfo = schelper.GetSystemConfig("1");
            hidBlogMaxPVMoney.Value = scinfo.BlogMaxPVMoney.ToString();
            litBlogMaxPVMoney.Text = scinfo.BlogMaxPVMoney.ToString();
        }
        #endregion

        #region 提交
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            Users uinfo = UserBase.GetCurrentUser();
            if (uinfo == null)
            {
                Response.Redirect("../Login.aspx");
                return;
            }
            string blogbigtype = rblBlogBigType.SelectedValue ;
            
            string blogtype = rblBlogType.SelectedValue;
            string companyid = "0";
            if (licompany.Visible)
            {
                companyid = rblCompany.SelectedValue;
            }
            string blogtypename = rblBlogType.SelectedItem.Text;
            string title = txtTitle.Text.Trim();
            string keyword = txtKeyWord.Text.Trim();
            keyword=keyword.Replace("，"," ");
            keyword = keyword.Replace(",", " ");
            int moneytype = 0;
            if (rbMianFei.Checked)
            {
                moneytype = 0;
            }
            else if (rbShouFei.Checked)
            {
                moneytype = 1;
            }
            string costmoney = txtCostMoney.Text.Trim();
            float costmoneyfloat = (float)Convert.ToDouble(costmoney);

            //判断费用是否超过系统设置最大值
            SystemConfig scinfo = new SystemConfig();
            SystemConfigHelper schelper = new SystemConfigHelper();
            scinfo = schelper.GetSystemConfig("1");

            if (moneytype == 0)
            {
                costmoneyfloat = 0;
            }
            else
            {
                
                if (costmoneyfloat > scinfo.BlogMaxPVMoney)
                {
                    Tools.Alert("费用不能超过" + scinfo.BlogMaxPVMoney + "个友赢豆，请重新输入");
                    return;
                }
            }

            string fileFullName = "";
            string filePath = "";
            string fileFolder = "/Files/mp3/";
            //判断类型 MP3类型需选择文件
            if (blogbigtype.ToLower() == "mp3")
            {
                if (fuFile.HasFile)
                {
                    //判断文件的大小
                    string FileName = fuFile.FileName.ToString();
                    string ExtenName = System.IO.Path.GetExtension(FileName);//获取扩展名
                    if (ExtenName.ToLower() == ".mp3")
                    {
                        //判断文件的大小
                        //系统设置最大文件大小
                        int filemaxlength = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["filemaxlength"] + "");
                        if (fuFile.PostedFile.ContentLength <= filemaxlength)
                        {
                            string serverPath = "..\\Files\\mp3\\";
                            filePath = Server.MapPath(serverPath);

                            if (!System.IO.Directory.Exists(filePath))
                            {
                                System.IO.Directory.CreateDirectory(filePath);
                            }

                            string filename = DateTime.Now.ToString("yyyyMMddhhmmss");

                            fileFullName = filename + ExtenName;
                            filePath += fileFullName;
                            fuFile.SaveAs(filePath);
                        }
                        else
                        {
                            Tools.Alert("文件超过规定大小，请重新上传");
                            return;
                        }

                    }
                    else
                    {
                        Tools.Alert("文件格式不正确，后缀名为.mp3");
                        return;
                    }
                }
                else
                {
                    Tools.Alert("请上传mp3文件");
                    return;
                }
            }

            int isindex = 0;
            if (rbIsIndexNo.Checked)
            {
                isindex = 0;
            }
            else if (rbIsIndexYes.Checked)
            {
                isindex = 1;
            }

            string blogcontent = txtContent.Value.Trim();

            int otheredit = 0;
            if (cbOtherEdit.Checked)
            {
                otheredit = 1;
            }

            Blog binfo = new Blog();
            
            binfo.BlogBigType = blogbigtype;
            binfo.BlogTypeID = blogtype;
            if (blogbigtype.ToLower() == "mp3")
            {
                binfo.FilePath = fileFolder + fileFullName;
            }
            binfo.CompanyID = companyid;
            binfo.BlogTypeName = blogtypename;
            binfo.Title = title;
            binfo.KeyWord = keyword;
            binfo.MoneyType = moneytype;
            binfo.CostMoney = costmoneyfloat;
            binfo.BlogContent = blogcontent;
            binfo.IsIndex = isindex;
            binfo.UsersID = uinfo.ID;
            binfo.RoleID = uinfo.RoleID;
            binfo.NickName = uinfo.NickName;
            binfo.OtherEdit = otheredit;
            binfo.Flag = 0;

            BlogHelper bhelper = new BlogHelper();

            //得到该博客中第一张图片的地址
            string firstpicpath = bhelper.GetFirstPicPath(blogcontent);
            if (firstpicpath != "")
            {
                binfo.HasPic = 1;
                
                if (firstpicpath.Contains("http"))
                {
                    binfo.FirstPicPath = firstpicpath;
                }
                else
                {
                    string serverpath = UserBase.GetServerPath();
                    binfo.FirstPicPath = serverpath + firstpicpath;
                }
            }
            bhelper.AddBlog(binfo);

            //更新用户表中用户发表博客的数量
            int blognum = uinfo.BlogNum;
            blognum = blognum + 1;
            uinfo.BlogNum = blognum;
            UsersHelper uhelper = new UsersHelper();
            uhelper.EditUsers(uinfo);

            int blogmoneynum = scinfo.BlogMoneyNum;
            float blogmoney =(float) scinfo.BlogMoney;

            if (blogmoney > 0)
            {
                //用户发表前5篇创作奖励1元钱 可以系统配置
                CashFlowHelper cfhelper = new CashFlowHelper();
                Criteria c = new Criteria();
                c.Add(CriteriaType.Equals, "UsersID", uinfo.ID);
                c.Add(CriteriaType.Equals, "Type", 8);
                c.Add(CriteriaType.Equals, "Description", "发表创作");
                int count = cfhelper.QueryCashFlowCountBySearch(c);
                if (count < blogmoneynum)
                {
                    //增加奖励记录
                    CashFlow cfinfo = new CashFlow();
                    cfinfo.UsersID = uinfo.ID;
                    cfinfo.Money = blogmoney;
                    cfinfo.Type = 8;
                    cfinfo.Description = "发表创作";
                    cfhelper.AddCashFlow(cfinfo);
                }
            }

            Tools.AlertAndRedirect("创作成功！", "BlogList.aspx");
        }
        #endregion

        #region 加载我加入的小组
        private void BindCompany()
        {
            Users uinfo = UserBase.GetCurrentUser();
            string userid = uinfo.ID;

            UserCompanyHelper uchelper=new UserCompanyHelper();
            DataSet dsCompany = uchelper.GetUserAddCompany(userid,999);

            if (dsCompany != null && dsCompany.Tables[0].Rows.Count > 0)
            {
                licompany.Visible = true;

                rblCompany.DataSource = dsCompany;
                rblCompany.DataTextField = "CompanyName";
                rblCompany.DataValueField = "id";
                rblCompany.DataBind();

                ListItem li = new ListItem();
                li.Value = "0";
                li.Text = "不分配小组";
                li.Selected = true;
                rblCompany.Items.Insert(0, li);


                if (!string.IsNullOrEmpty(companyid))
                {
                    rblCompany.SelectedValue = companyid;
                }
            }
            else//加入小组为空
            {
                licompany.Visible = false;
            }
        }
        #endregion

        #region 类型改变
        protected void rblBlogBigType_SelectedIndexChanged(object sender, EventArgs e)
        {
            string blogbigtype = rblBlogBigType.SelectedValue;
            BlogTypeHelper bthelper = new BlogTypeHelper();
            Criteria c = new Criteria();
            c.Add(CriteriaType.Equals, "BlogBigType", blogbigtype);
            c.Add(CriteriaType.Equals, "Flag", 0);
            List<BlogType> btlist = bthelper.QueryBlogTypeBySearch(c, new Order[] { new Order("CreateDate", OrderMode.Desc) });

            rblBlogType.DataSource = btlist;
            rblBlogType.DataTextField = "BlogTypeName";
            rblBlogType.DataValueField = "ID";
            rblBlogType.DataBind();

            if (btlist != null && btlist.Count > 0)
            {
                rblBlogType.Items[0].Selected = true;
            }

            //文件
            if (blogbigtype.ToLower() == "mp3")
            {
                lifile.Visible = true;
            }
            else
            {
                lifile.Visible = false;
            }
        }
        #endregion

        #region 将用户加入小组
        private void AddCompany(string companyid)
        {
            UserCompanyHelper uchelper = new UserCompanyHelper();
            Users uinfo = UserBase.GetCurrentUser();
            //判断当前用户是否为该小组成员
            Criteria c = new Criteria();
            c.Add(CriteriaType.Equals, "UsersID", uinfo.ID);
            c.Add(CriteriaType.Equals, "CompanyID", companyid);
            List<UserCompany> uclist = uchelper.QueryUserCompanyBySearch(c, null);
            if (uclist != null && uclist.Count > 0)
            {
                int status = uclist[0].Status;
                if (status == 0)//提交申请待审批
                {
                    Tools.Alert("还不是该小组成员，提交申请待审批");
                    return;
                }
                else if (status == 1)//审批通过
                {
                    
                }
                else if (status == 2)//审批拒绝
                {
                    Companys cinfo = new Companys();
                    CompanysHelper chelper = new CompanysHelper();
                    cinfo = chelper.GetCompanys(companyid);
                    int type = cinfo.Type;
                    if (type == 1)//需审批
                    {
                        Tools.Alert("还不是该小组成员，请先加入该小组");
                        return;
                    }
                    else if (type == 2)//不需审批
                    {
                        //修改申请记录
                        UserCompany ucinfo = new UserCompany();
                        ucinfo = uclist[0];
                        ucinfo.Status = 1;
                        uchelper.EditUserCompany(ucinfo);

                        //修改小组人数
                        int usernum = cinfo.UserNum;
                        usernum = usernum + 1;
                        cinfo.UserNum = usernum;
                        chelper.EditCompanys(cinfo);
                    }

                }
            }
            else
            {
                //加载公司信息
                Companys cinfo = new Companys();
                CompanysHelper chelper = new CompanysHelper();
                cinfo = chelper.GetCompanys(companyid);
                int type = cinfo.Type;//1需要审批2不需要审批
                if (type == 1)
                {
                    Tools.Alert("还不是该小组成员，请先加入该小组");
                    return;
                }
                else if (type == 2)//不需要审批直接插入记录
                {
                    UserCompany ucinfo = new UserCompany();
                    ucinfo.UsersID = uinfo.ID;
                    ucinfo.NickName = uinfo.NickName;
                    ucinfo.CompanyID = companyid;
                    ucinfo.CompanyOwnerID = cinfo.OwnerUserID;
                    ucinfo.Status = 1;
                    uchelper.AddUserCompany(ucinfo);

                    //修改小组人数
                    int usernum = cinfo.UserNum;
                    usernum = usernum + 1;
                    cinfo.UserNum = usernum;
                    chelper.EditCompanys(cinfo);
                }
            }
        }
        #endregion

        #region 暂时保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Users uinfo = UserBase.GetCurrentUser();
            if (uinfo == null)
            {
                Response.Redirect("../Login.aspx");
                return;
            }
            string blogbigtype = rblBlogBigType.SelectedValue;

            string blogtype = rblBlogType.SelectedValue;
            string companyid = "0";
            if (licompany.Visible)
            {
                companyid = rblCompany.SelectedValue;
            }
            string blogtypename = rblBlogType.SelectedItem.Text;
            string title = txtTitle.Text.Trim();
            string keyword = txtKeyWord.Text.Trim();
            keyword = keyword.Replace("，", " ");
            keyword = keyword.Replace(",", " ");
            int moneytype = 0;
            if (rbMianFei.Checked)
            {
                moneytype = 0;
            }
            else if (rbShouFei.Checked)
            {
                moneytype = 1;
            }
            string costmoney = txtCostMoney.Text.Trim();
            float costmoneyfloat = (float)Convert.ToDouble(costmoney);

            //判断费用是否超过系统设置最大值
            SystemConfig scinfo = new SystemConfig();
            SystemConfigHelper schelper = new SystemConfigHelper();
            scinfo = schelper.GetSystemConfig("1");

            if (moneytype == 0)
            {
                costmoneyfloat = 0;
            }
            else
            {

                if (costmoneyfloat > scinfo.BlogMaxPVMoney)
                {
                    Tools.Alert("费用不能超过" + scinfo.BlogMaxPVMoney + "个友赢豆，请重新输入");
                    return;
                }
            }

            int isindex = 0;
            if (rbIsIndexNo.Checked)
            {
                isindex = 0;
            }
            else if (rbIsIndexYes.Checked)
            {
                isindex = 1;
            }

            string blogcontent = txtContent.Value.Trim();

            int otheredit = 0;
            if (cbOtherEdit.Checked)
            {
                otheredit = 1;
            }

            Blog binfo = new Blog();

            binfo.BlogBigType = blogbigtype;
            binfo.BlogTypeID = blogtype;
            binfo.CompanyID = companyid;
            binfo.BlogTypeName = blogtypename;
            binfo.Title = title;
            binfo.KeyWord = keyword;
            binfo.MoneyType = moneytype;
            binfo.CostMoney = costmoneyfloat;
            binfo.BlogContent = blogcontent;
            binfo.IsIndex = isindex;
            binfo.UsersID = uinfo.ID;
            binfo.RoleID = uinfo.RoleID;
            binfo.NickName = uinfo.NickName;
            binfo.OtherEdit = otheredit;
            binfo.Flag = -1;//0有效9自己删除-9后台屏蔽-1保存

            BlogHelper bhelper = new BlogHelper();
            bhelper.AddBlog(binfo);

            Tools.AlertAndRedirect("暂时保存成功！", "BlogAdd.aspx");
        }
        #endregion

        #region 加载内容
        private void LoadContent()
        {
            //判断该用户是否存在暂时保存的创作 如果有则加载出 
            Users uinfo = UserBase.GetCurrentUser();
            if (uinfo == null)
            {
                Response.Redirect("../Login.aspx");
                return;
            }
            BlogHelper bhelper = new BlogHelper();
            Criteria c = new Criteria();
            c.Add(CriteriaType.Equals, "Flag", -1);
            c.Add(CriteriaType.Equals, "UsersID", uinfo.ID);
            List<Blog> blist = bhelper.QueryBlogBySearch(c, null);
            if (blist != null && blist.Count > 0)
            {
                Blog binfo = blist[0];
                //绑定信息
                rblBlogBigType.SelectedValue = binfo.BlogBigType;
                rblBlogType.SelectedValue = binfo.BlogTypeID;
                rblCompany.SelectedValue = binfo.CompanyID;
                txtTitle.Text = binfo.Title;
                txtKeyWord.Text = binfo.KeyWord;
                string moneytype = binfo.MoneyType.ToString();
                if (moneytype == "0")
                {
                    rbMianFei.Checked = true;
                }
                else
                {
                    rbShouFei.Checked = true;
                }
                txtCostMoney.Text = binfo.CostMoney.ToString();
                txtContent.Value = binfo.BlogContent;
                string isindex = binfo.IsIndex.ToString();
                if (isindex == "0")
                {
                    rbIsIndexNo.Checked = true;
                }
                else
                {
                    rbIsIndexYes.Checked = true;
                }
                string otheredit = binfo.OtherEdit.ToString();
                if (otheredit == "1")
                {
                    cbOtherEdit.Checked = true;
                }
            }
        }
        #endregion
    }
}